package com.summer.study.leetcode.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther: 杨杰
 * @date: 2019/7/25 14:45
 * @description: 3个线程将ABC按顺序多次输出
 */
public class ReentrantLockABCDemo {

    private int num;

    private int status;

    private ReentrantLock lock;

    private Condition conditionA;

    private Condition conditionB;

    private Condition conditionC;

    ReentrantLockABCDemo(int num) {
        this.num = num;
        status = 1;
        lock = new ReentrantLock();
        conditionA = lock.newCondition();
        conditionB = lock.newCondition();
        conditionC = lock.newCondition();
    }

    private void printA() {
        lock.lock();
        try {
            for (int i = 0; i < num; i++) {
                while (status != 1) {
                    conditionA.await();
                }
                System.out.print("A");
                status = 2;
                conditionB.signal();
            }
        } catch (InterruptedException e) {

        } finally {
            lock.unlock();
        }
    }

    private void printB() {
        lock.lock();
        try {
            for (int i = 0; i < num; i++) {
                while (status != 2) {
                    conditionB.await();
                }
                System.out.print("B");
                status = 3;
                conditionC.signal();
            }
        } catch (InterruptedException e) {

        } finally {
            lock.unlock();
        }
    }

    private void printC() {
        lock.lock();
        try {
            for (int i = 0; i < num; i++) {
                while (status != 3) {
                    conditionC.await();
                }
                System.out.println("C");
                status = 1;
                conditionA.signal();
            }
        } catch (InterruptedException e) {

        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockABCDemo demo = new ReentrantLockABCDemo(1000);
        new Thread(() -> {
            demo.printA();
        }).start();
        new Thread(() -> {
            demo.printB();
        }).start();
        new Thread(() -> {
            demo.printC();
        }).start();
    }

}
